package com.redis.client.util;

import com.alibaba.fastjson.JSON;
import com.redis.client.bean.Account;
import com.redis.client.bean.PersistBean;
import com.redis.client.manage.Persistent;
import com.sun.deploy.util.StringUtils;

import java.io.*;

/**
 * @author hetao
 */
public class JsonUtil {

    public static final String CONFIG_NAME="config.txt";

    public static PersistBean getPersistBean() {
        String jsonStr = readFile(CONFIG_NAME);

        return JSON.parseObject(jsonStr, PersistBean.class);
    }

    public static boolean setPersistBean(PersistBean bean) {
        return saveFile(CONFIG_NAME, JSON.toJSONString(bean));
    }

    public static String readFile(String fileName) {

        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            if(!jsonFile.exists()) {
                jsonFile.createNewFile();
            }
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static boolean saveFile(String fileName, String data) {
        BufferedWriter writer = null;
        try {
            File file = new File(fileName);
            if(!file.exists()) {
                if(!file.createNewFile()) {
                    return false;
                }
            }
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false), "UTF-8"));
            writer.write(data);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
